package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityDamageByEntityEvent;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.attribute.EntityAttributeInstance;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;

import java.util.Optional;
import java.util.function.Predicate;

public class ObsidianEffect extends AbstractEffect {

    @Listener
    public void tick(WorldTickEvent e) {
        for (Entity ent : e.getWorld().getEntities()) {
            PlayerEntity entity = PlayerManager.get(ent.getUuid());
            if (entity instanceof ServerPlayerEntity livingEntity) {
                EntityAttributeModifier modifier = new EntityAttributeModifier(livingEntity.getUuid(), "ObsidianEffect", 5, EntityAttributeModifier.Operation.MULTIPLY_BASE);
                if (!predicateArmor().test(livingEntity)) {
                    Optional.ofNullable(livingEntity.getAttributeInstance(EntityAttributes.GENERIC_MAX_HEALTH)).ifPresent(ins->{
                       if(ins.hasModifier(modifier)){
                           ins.removeModifier(modifier);
                           livingEntity.setHealth(livingEntity.getHealth()>20?20:livingEntity.getHealth());
                       }
                    });
                    continue;
                }
                Optional<EntityAttributeInstance> instance = Optional.ofNullable(livingEntity.getAttributeInstance(EntityAttributes.GENERIC_MAX_HEALTH));
                if (instance.isPresent()) {
                    EntityAttributeInstance eai = instance.get();
                    if (!eai.hasModifier(modifier)) {
                        eai.addTemporaryModifier(modifier);
                        livingEntity.setHealth(120);
                    }
                    //todo strange
                }
            }
        }
    }

    @Listener
    public void onDamageByEntity(EntityDamageByEntityEvent e) {
        if (!predicateArmor().test(e.getEntity())) {
            return;
        }
        e.setDamage(1);
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.OBSIDIAN);
    }

}
